/*
 * Copyright (C) 2015-2020 Alibaba Group Holding Limited
 */
/**
 * @file main.c
 *
 * This file includes the entry code of link sdk related demo
 *
 */

#include <string.h>
#include <stdio.h>
#include <aos/kernel.h>
#include "netmgr.h"
#include <uservice/uservice.h>
#include <uservice/eventid.h>
#include "sh1106.h"
#include "time.h"
//#include "posix/timer.h"
char ip_addr[32] = {0};//定义IP地址的字符串
struct timespec timevalue;//定义时间变量
struct tm * info;//定义结构体指针变量
extern int demo_main(int argc, char *argv[]);

static int _ip_got_finished = 0;
//netmgr -t wifi -c dayueyue zhangmingyue0807
static void entry_func(void *data)
{
    demo_main(0 , NULL);
}
static void wifi_event_cb(uint32_t event_id, const void *param, void *context)
{
    
    aos_task_t task;
    aos_status_t ret;
    if (event_id != EVENT_NETMGR_DHCP_SUCCESS)
        return;

    if (_ip_got_finished != 0)
        return;

    _ip_got_finished = 1;
    ret = aos_task_create(&task, "linksdk_demo", entry_func,
                          NULL, NULL, 6048, AOS_DEFAULT_APP_PRI, AOS_TASK_AUTORUN);
    if (ret < 0) {
        printf("create linksdk demo task failed, ret = %ld \r\n", ret);
    }
}

int application_start(int argc, char *argv[])
{
    char buf[50] = {0};
    aos_set_log_level(AOS_LL_DEBUG);
    event_service_init(NULL);
    netmgr_service_init(NULL);
    netmgr_set_auto_reconnect(NULL, true);
    netmgr_wifi_set_auto_save_ap(true);
    sh1106_init();
    event_subscribe(EVENT_NETMGR_DHCP_SUCCESS, wifi_event_cb, NULL);
    while (1) {
        if(_ip_got_finished){
            netmgr_wifi_get_ip_addr(&ip_addr);//获取网络ip地址
            OLED_Clear();
            sprintf(buf,"ip:%s",ip_addr);
            OLED_Show_String(5,5,buf,12,1);
            OLED_Refresh_GRAM();

            clock_gettime(CLOCK_REALTIME,&timevalue);
            info = gmtime(&timevalue);
            sprintf(buf,"%4d.%2d.%2d  %2d.%2d.%2d",info->tm_year+1900,info->tm_mon+1,info->tm_mday,(info->tm_hour+8)%24,info->tm_min,info->tm_sec);
            OLED_Show_String(5,15,buf,12,1);
            OLED_Refresh_GRAM();
        }
        aos_msleep(1000);        
    };
    return 0;
}